#include "swoole.h"

void myserver_init(void){

	if(SwooleG.running){
		return ;
	}

	bzero(&SwooleG,sizeof(SwooleG));

	SwooleG.pid = getpid();
	SwooleG.running = 1;
	SwooleG.cpu_num = sysconf(_SC_NPROCESSORS_ONLN);
	SwooleG.memory_pool = swMemoryGlobal_new(SW_GLOBAL_MEMORY_PAGESIZE,1);
	if(SwooleG.memory_pool == NULL){
		printf("[Master] Fatal Error: global memory allocation failure.\n");
		exit(1);
	}

	swSignalfd_init();
	SwooleG.use_signalfd = 1;
}

void myserver_clean(){
	if(SwooleG.memory_pool != NULL){
		if(SwooleG.main_reactor){
			SwooleG.main_reactor->free(SwooleG.main_reactor);
		}

		SwooleG.memory_pool->destroy(SwooleG.memory_pool);
		bzero(&SwooleG,sizeof(SwooleG));
	}
}

void swoole_fcntl_set_option(int sock, int nonblock, int cloexec)
{
    int opts, ret;

    if (nonblock >= 0)
    {
        do
        {
            opts = fcntl(sock, F_GETFL);
        }
        while (opts < 0 && errno == EINTR);

        if (opts < 0)
        {
            swSysError("fcntl(%d, GETFL) failed.", sock);
        }

        if (nonblock)
        {
            opts = opts | O_NONBLOCK;
        }
        else
        {
            opts = opts & ~O_NONBLOCK;
        }

        do
        {
            ret = fcntl(sock, F_SETFL, opts);
        }
        while (ret < 0 && errno == EINTR);

        if (ret < 0)
        {
            swSysError("fcntl(%d, SETFL, opts) failed.", sock);
        }
    }

#ifdef FD_CLOEXEC
    if (cloexec >= 0)
    {
        do
        {
            opts = fcntl(sock, F_GETFD);
        }
        while (opts < 0 && errno == EINTR);

        if (opts < 0)
        {
            swSysError("fcntl(%d, GETFL) failed.", sock);
        }

        if (cloexec)
        {
            opts = opts | FD_CLOEXEC;
        }
        else
        {
            opts = opts & ~FD_CLOEXEC;
        }

        do
        {
            ret = fcntl(sock, F_SETFD, opts);
        }
        while (ret < 0 && errno == EINTR);

        if (ret < 0)
        {
            swSysError("fcntl(%d, SETFD, opts) failed.", sock);
        }
    }
#endif
}
